const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const router = express.Router();
const { uploadToQiniu } = require('../utils/qiniu');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../../uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

// 文件过滤器
const fileFilter = function (req, file, cb) {
  // 只允许上传图片
  if (!file.mimetype.startsWith('image/')) {
    return cb(new Error('只能上传图片文件！'));
  }
  cb(null, true);
};

// 配置multer
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制10MB
  }
});

// 上传文件
router.post('/', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请选择要上传的文件' });
    }

    // 上传到七牛云
    const qiniuUrl = await uploadToQiniu(req.file.path, req.file.originalname);

    // 删除本地临时文件
    fs.unlinkSync(req.file.path);

    res.json({
      url: qiniuUrl,
      name: req.file.originalname,
      size: req.file.size,
      type: req.file.mimetype
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({ error: '文件上传失败' });
  }
});

// 多文件上传
router.post('/multiple', upload.array('files', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ error: '没有上传文件' });
    }
    
    const baseUrl = `${req.protocol}://${req.get('host')}`;
    const responseData = [];
    
    for (const file of req.files) {
      const fileUrl = `/uploads/${file.filename}`;
      
      // 获取图片尺寸（如果是图片）
      let width = null;
      let height = null;
      
      if (file.mimetype.startsWith('image/')) {
        try {
          const sharp = require('sharp');
          const metadata = await sharp(file.path).metadata();
          width = metadata.width;
          height = metadata.height;
        } catch (error) {
          console.log('获取图片尺寸失败:', error.message);
        }
      }
      
      responseData.push({
        id: uuidv4(),
        name: file.originalname,
        alternativeText: null,
        caption: null,
        width: width,
        height: height,
        formats: null,
        hash: file.filename.split('.')[0],
        ext: path.extname(file.originalname),
        mime: file.mimetype,
        size: (file.size / 1024).toFixed(2), // KB
        url: fileUrl,
        previewUrl: null,
        provider: 'local',
        provider_metadata: null,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      });
    }
    
    res.json(responseData);
  } catch (error) {
    console.error('多文件上传失败:', error);
    
    // 删除已上传的文件
    if (req.files) {
      req.files.forEach(file => {
        try {
          fs.unlinkSync(file.path);
        } catch (deleteError) {
          console.error('删除文件失败:', deleteError);
        }
      });
    }
    
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ error: '文件大小超出限制' });
    }
    
    res.status(500).json({ error: error.message || '文件上传失败' });
  }
});

module.exports = router;